package com.ltu.timkor6.gamesite.server;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ltu.timkor6.gamesite.shared.UserInfo;

@SuppressWarnings("serial")
public class GameSiteServiceImpl extends RemoteServiceServlet
{
	//private static final Logger LOG = Logger.getLogger(UsersServiceImpl.class.getName());
	protected static final PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("transactions-optional");
	
	protected static final String USER_SESSION = "GWTAppUser";
	
	// Only saved between one service implementation at a time.
	protected UserInfo userInfo = null;
	
	public GameSiteServiceImpl()
	{
	}
	
	protected void checkLogin(String where)
	{
		if(userInfo == null)
		{
			System.out.println("Error: No user in at " + where + ".");
		}
		else
		{
			System.out.println("User " + this.userInfo.getUserName() + " is signed in at " + where + ".");
		}
	}
	
	/**
	 * Must be run by every module to get a user session.
	 */
	public boolean checkUser()
	{
		this.userInfo = this.getUserFromSession();
		return (this.userInfo != null);
	}
	
	/**
	 * Gets the session from the server.
	 * Cannot be called from a ServiceImpl constructor. Must be called after.
	 */
	protected UserInfo getUserFromSession()
	{
		HttpSession session = this.getThreadLocalRequest().getSession();
		return (UserInfo) session.getAttribute(USER_SESSION);
	}
	
	protected void invalidateSession()
	{
		HttpSession session = this.getThreadLocalRequest().getSession();
		session.invalidate();
	}
	
	protected void setUserInSession(UserInfo userInfo)
	{
		HttpSession session = this.getThreadLocalRequest().getSession();
		session.setAttribute(USER_SESSION, userInfo);
	}
	
	/**
	 * Get the persistence manager.
	 * @return
	 */
	protected PersistenceManager getPersistenceManager()
	{
		return PMF.getPersistenceManager();
	}
}
